<template>
  <div>
    <el-dialog
      v-model="show"
      :title="title"
      width="500"
      draggable
      destroy-on-close
      @close="reset"
    >
      <div>
        <el-form
          :model="formData"
          label-width="auto"
          style="max-width: 600px"
          :rules="rules"
          ref="ruleForm"
          :mode="ruleModel"
        >
          <el-form-item label="字段名称" prop="key">
            <el-input v-model="formData.key" :disabled="formData.key==''?false:true" />
          </el-form-item>
          <el-form-item label="字段值" prop="value">
            <el-input v-model="formData.value" />
          </el-form-item>
          <el-form-item label="字段类型">
            <el-select v-model="formData.type" placeholder="请输入字段类型">
              <el-option label="通用" value="0" />
              <el-option label="支付" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="formData.status">
              <el-radio value="0">禁用</el-radio>
              <el-radio value="1">启用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="字段描述">
            <el-input
              v-model="formData.note"
              type="textarea"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="reset">取消</el-button>
          <el-button type="primary" @click="onSubmit"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { defineExpose, ref, defineEmits } from "vue";

const emits = defineEmits(["common"]);
const show = ref(false);
const title = ref("添加字典");

const ruleForm = ref();
const rules = ref({
  key: [{ required: true, message: "请输入字段名称", trigger: "blur" }],
  value: [{ required: true, message: "请输入字段值", trigger: "blur" }],
});

const formData = ref({
  key: "",
  value: "",
  status: "1",
  type: "0",
  note: "",
  flag: 1,
});

const open = (item, type) => {
  show.value = true;
  title.value = type;
  if ("修改字段" === type) {
    formData.value.key = item.key;
    formData.value.note = item.note;
    formData.value.status = item.status == 0 ? "0" : "1";
    formData.value.type = item.type === 1 ? "1" : "0";
    formData.value.value = item.value;
    formData.value.flag = 0;
  }
};

const ruleModel = ref({
  key: "",
  value: "",
});

const onSubmit = () => {
  ruleForm.value.validate((valid) => {
    if (valid) {
      console.log("==========", formData.value);
      emits("common", formData.value);
      reset();
    }
  });
};

const reset = () => {
  formData.value = {
    key: "",
    value: "",
    status: "1",
    type: "0",
    note: "",
    flag: 1,
  };
  show.value = false;
};

defineExpose({
  open,
});
</script>

<style></style>
